{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Network in Network (NiN)\n",
    "\n",
    ":label:`sec_nin`\n",
    "\n",
    "\n",
    "LeNet, AlexNet, and VGG all share a common design pattern:\n",
    "extract features exploiting *spatial* structure\n",
    "via a sequence of convolutions and pooling layers\n",
    "and then post-process the representations via fully-connected layers.\n",
    "The improvements upon LeNet by AlexNet and VGG mainly lie\n",
    "in how these later networks widen and deepen these two modules.\n",
    "Alternatively, one could imagine using fully-connected layers\n",
    "earlier in the process.\n",
    "However, a careless use of dense layers might give up the\n",
    "spatial structure of the representation entirely,\n",
    "Network in Network (NiN) blocks offer an alternative.\n",
    "They were proposed in :cite:`Lin.Chen.Yan.2013` based on a very simple insight---to\n",
    "use an MLP on the channels for each pixel separately.\n",
    "\n",
    "## NiN Blocks\n",
    "\n",
    "Recall that the inputs and outputs of convolutional layers\n",
    "consist of four-dimensional arrays with axes\n",
    "corresponding to the batch, channel, height, and width.\n",
    "Also recall that the inputs and outputs of fully-connected layers\n",
    "are typically two-dimensional arrays corresponding to the batch, and features.\n",
    "The idea behind NiN is to apply a fully-connected layer\n",
    "at each pixel location (for each height and  width).\n",
    "If we tie the weights across each spatial location,\n",
    "we could think of this as a $1\\times 1$ convolutional layer\n",
    "(as described in :numref:`sec_channels`)\n",
    "or as a fully-connected layer acting independently on each pixel location.\n",
    "Another way to view this is to think of each element in the spatial dimension\n",
    "(height and width) as equivalent to an example\n",
    "and the channel as equivalent to a feature.\n",
    ":numref:`fig_nin` illustrates the main structural differences\n",
    "between NiN and AlexNet, VGG, and other networks.\n",
    "\n",
    "![The figure on the left shows the network structure of AlexNet and VGG, and the figure on the right shows the network structure of NiN. ](https://raw.githubusercontent.com/d2l-ai/d2l-en/master/img/nin.svg)\n",
    "\n",
    ":width:`600px`\n",
    "\n",
    "\n",
    ":label:`fig_nin`\n",
    "\n",
    "\n",
    "\n",
    "The NiN block consists of one convolutional layer\n",
    "followed by two $1\\times 1$ convolutional layers that act as\n",
    "per-pixel fully-connected layers with ReLU activations.\n",
    "The convolution width of the first layer is typically set by the user.\n",
    "The subsequent widths are fixed to $1 \\times 1$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load ../utils/djl-imports\n",
    "%load ../utils/plot-utils\n",
    "%load ../utils/Training.java\n",
    "%load ../utils/Accumulator.java"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import ai.djl.basicdataset.cv.classification.*;\n",
    "import ai.djl.metric.*;\n",
    "import org.apache.commons.lang3.ArrayUtils;"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "2"
    }
   },
   "outputs": [],
   "source": [
    "// setting the seed for demonstration purpose. You can remove it when you run the notebook\n",
    "Engine.getInstance().setRandomSeed(5555);\n",
    "\n",
    "public SequentialBlock niNBlock(int numChannels, Shape kernelShape, \n",
    "                     Shape strideShape, Shape paddingShape){\n",
    "    \n",
    "    SequentialBlock tempBlock = new SequentialBlock();\n",
    "    \n",
    "    tempBlock.add(Conv2d.builder()\n",
    "              .setKernelShape(kernelShape)\n",
    "              .optStride(strideShape)\n",
    "              .optPadding(paddingShape)\n",
    "              .setFilters(numChannels)\n",
    "              .build())\n",
    "        .add(Activation::relu)\n",
    "        .add(Conv2d.builder()\n",
    "              .setKernelShape(new Shape(1, 1))\n",
    "              .setFilters(numChannels)\n",
    "              .build())\n",
    "        .add(Activation::relu)\n",
    "        .add(Conv2d.builder()\n",
    "              .setKernelShape(new Shape(1, 1))\n",
    "              .setFilters(numChannels)\n",
    "              .build())\n",
    "        .add(Activation::relu); \n",
    "    \n",
    "    return tempBlock;\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## NiN Model\n",
    "\n",
    "The original NiN network was proposed shortly after AlexNet\n",
    "and clearly draws some inspiration.\n",
    "NiN uses convolutional layers with window shapes\n",
    "of $11\\times 11$, $5\\times 5$, and $3\\times 3$,\n",
    "and the corresponding numbers of output channels are the same as in AlexNet. Each NiN block is followed by a maximum pooling layer\n",
    "with a stride of 2 and a window shape of $3\\times 3$.\n",
    "\n",
    "Once significant difference between NiN and AlexNet\n",
    "is that NiN avoids dense connections altogether.\n",
    "Instead, NiN uses an NiN block with a number of output channels equal to the number of label classes, followed by a *global* average pooling layer,\n",
    "yielding a vector of [logits](https://en.wikipedia.org/wiki/Logit).\n",
    "One advantage of NiN's design is that it significantly\n",
    "reduces the number of required model parameters.\n",
    "However, in practice, this design sometimes requires\n",
    "increased model training time."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "9"
    }
   },
   "outputs": [],
   "source": [
    "SequentialBlock block = new SequentialBlock();\n",
    "\n",
    "block.add(niNBlock(96, new Shape(11, 11), new Shape(4, 4), new Shape(0, 0)))\n",
    "     .add(Pool.maxPool2dBlock(new Shape(3, 3), new Shape(2, 2)))\n",
    "     .add(niNBlock(256, new Shape(5, 5), new Shape(1, 1), new Shape(2, 2)))\n",
    "     .add(Pool.maxPool2dBlock(new Shape(3, 3), new Shape(2, 2)))\n",
    "     .add(niNBlock(384, new Shape(3, 3), new Shape(1, 1), new Shape(1, 1)))\n",
    "     .add(Pool.maxPool2dBlock(new Shape(3, 3), new Shape(2, 2)))\n",
    "     .add(Dropout.builder().optRate(0.5f).build())\n",
    "     // There are 10 label classes\n",
    "     .add(niNBlock(10, new Shape(3, 3), new Shape(1, 1), new Shape(1, 1)))\n",
    "     // The global average pooling layer automatically sets the window shape\n",
    "     // to the height and width of the input\n",
    "     .add(Pool.globalAvgPool2dBlock())\n",
    "     // Transform the four-dimensional output into two-dimensional output\n",
    "     // with a shape of (batch size, 10)\n",
    "     .add(Blocks.batchFlattenBlock());"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We create a data example to see the output shape of each block."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "float lr = 0.1f;\n",
    "Model model = Model.newInstance(\"cnn\");\n",
    "model.setBlock(block);\n",
    "\n",
    "Loss loss = Loss.softmaxCrossEntropyLoss();\n",
    "\n",
    "Tracker lrt = Tracker.fixed(lr);\n",
    "Optimizer sgd = Optimizer.sgd().setLearningRateTracker(lrt).build();\n",
    "\n",
    "DefaultTrainingConfig config = new DefaultTrainingConfig(loss).optOptimizer(sgd) // Optimizer (loss function)\n",
    "                .optDevices(Engine.getInstance().getDevices(1)) // single GPU\n",
    "                .addEvaluator(new Accuracy()) // Model Accuracy\n",
    "                .addTrainingListeners(TrainingListener.Defaults.logging()); // Logging\n",
    "\n",
    "Trainer trainer = model.newTrainer(config);\n",
    "\n",
    "NDManager manager = NDManager.newBaseManager();\n",
    "NDArray X = manager.randomUniform(0f, 1.0f, new Shape(1, 1, 224, 224));\n",
    "trainer.initialize(X.getShape());\n",
    "\n",
    "Shape currentShape = X.getShape();\n",
    "\n",
    "for (int i = 0; i < block.getChildren().size(); i++) {\n",
    "\n",
    "    Shape[] newShape = block.getChildren().get(i).getValue().getOutputShapes(new Shape[]{currentShape});\n",
    "    currentShape = newShape[0];\n",
    "    System.out.println(block.getChildren().get(i).getKey() + \" layer output : \" + currentShape);\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Data Acquisition and Training\n",
    "\n",
    "As before we use Fashion-MNIST to train the model.\n",
    "NiN's training is similar to that for AlexNet and VGG,\n",
    "but it often uses a larger learning rate."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "int batchSize = 128;\n",
    "int numEpochs = Integer.getInteger(\"MAX_EPOCH\", 10);\n",
    "\n",
    "double[] trainLoss;\n",
    "double[] testAccuracy;\n",
    "double[] epochCount;\n",
    "double[] trainAccuracy;\n",
    "\n",
    "epochCount = new double[numEpochs];\n",
    "\n",
    "for (int i = 0; i < epochCount.length; i++) {\n",
    "    epochCount[i] = i+1;\n",
    "}\n",
    "\n",
    "FashionMnist trainIter = FashionMnist.builder()\n",
    "        .addTransform(new Resize(224))\n",
    "        .addTransform(new ToTensor())\n",
    "        .optUsage(Dataset.Usage.TRAIN)\n",
    "        .setSampling(batchSize, true)\n",
    "        .optLimit(Long.getLong(\"DATASET_LIMIT\", Long.MAX_VALUE))\n",
    "        .build();\n",
    "\n",
    "FashionMnist testIter = FashionMnist.builder()\n",
    "        .addTransform(new Resize(224))\n",
    "        .addTransform(new ToTensor())\n",
    "        .optUsage(Dataset.Usage.TEST)\n",
    "        .setSampling(batchSize, true)\n",
    "        .optLimit(Long.getLong(\"DATASET_LIMIT\", Long.MAX_VALUE))\n",
    "        .build();\n",
    "\n",
    "trainIter.prepare();\n",
    "testIter.prepare();"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "Map<String, double[]> evaluatorMetrics = new HashMap<>();\n",
    "double avgTrainTimePerEpoch = Training.trainingChapter6(trainIter, testIter, numEpochs, trainer, evaluatorMetrics);"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "trainLoss = evaluatorMetrics.get(\"train_epoch_SoftmaxCrossEntropyLoss\");\n",
    "trainAccuracy = evaluatorMetrics.get(\"train_epoch_Accuracy\");\n",
    "testAccuracy = evaluatorMetrics.get(\"validate_epoch_Accuracy\");\n",
    "\n",
    "System.out.printf(\"loss %.3f,\", trainLoss[numEpochs - 1]);\n",
    "System.out.printf(\" train acc %.3f,\", trainAccuracy[numEpochs - 1]);\n",
    "System.out.printf(\" test acc %.3f\\n\", testAccuracy[numEpochs - 1]);\n",
    "System.out.printf(\"%.1f examples/sec\", trainIter.size() / (avgTrainTimePerEpoch / Math.pow(10, 9)));\n",
    "System.out.println();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![Contour Gradient Descent.](https://d2l-java-resources.s3.amazonaws.com/img/nin-plot.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "String[] lossLabel = new String[trainLoss.length + testAccuracy.length + trainAccuracy.length];\n",
    "\n",
    "Arrays.fill(lossLabel, 0, trainLoss.length, \"train loss\");\n",
    "Arrays.fill(lossLabel, trainAccuracy.length, trainLoss.length + trainAccuracy.length, \"train acc\");\n",
    "Arrays.fill(lossLabel, trainLoss.length + trainAccuracy.length,\n",
    "                trainLoss.length + testAccuracy.length + trainAccuracy.length, \"test acc\");\n",
    "\n",
    "Table data = Table.create(\"Data\").addColumns(\n",
    "            DoubleColumn.create(\"epoch\", ArrayUtils.addAll(epochCount, ArrayUtils.addAll(epochCount, epochCount))),\n",
    "            DoubleColumn.create(\"metrics\", ArrayUtils.addAll(trainLoss, ArrayUtils.addAll(trainAccuracy, testAccuracy))),\n",
    "            StringColumn.create(\"lossLabel\", lossLabel)\n",
    ");\n",
    "\n",
    "render(LinePlot.create(\"\", data, \"epoch\", \"metrics\", \"lossLabel\"),\"text/html\");"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "String[] lossLabel = new String[trainLoss.length + testAccuracy.length + trainAccuracy.length];\n",
    "\n",
    "Arrays.fill(lossLabel, 0, trainLoss.length, \"train loss\");\n",
    "Arrays.fill(lossLabel, trainAccuracy.length, trainLoss.length + trainAccuracy.length, \"train acc\");\n",
    "Arrays.fill(lossLabel, trainLoss.length + trainAccuracy.length,\n",
    "                trainLoss.length + testAccuracy.length + trainAccuracy.length, \"test acc\");\n",
    "\n",
    "Table data = Table.create(\"Data\").addColumns(\n",
    "    DoubleColumn.create(\"epoch\", ArrayUtils.addAll(epochCount, ArrayUtils.addAll(epochCount, epochCount))),\n",
    "    DoubleColumn.create(\"metrics\", ArrayUtils.addAll(trainLoss, ArrayUtils.addAll(trainAccuracy, testAccuracy))),\n",
    "    StringColumn.create(\"lossLabel\", lossLabel)\n",
    ");\n",
    "\n",
    "render(LinePlot.create(\"\", data, \"epoch\", \"metrics\", \"lossLabel\"),\"text/html\");"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Summary\n",
    "\n",
    "* NiN uses blocks consisting of a convolutional layer and multiple $1\\times 1$ convolutional layer. This can be used within the convolutional stack to allow for more per-pixel nonlinearity.\n",
    "* NiN removes the fully connected layers and replaces them with global average pooling (i.e., summing over all locations) after reducing the number of channels to the desired number of outputs (e.g., 10 for Fashion-MNIST).\n",
    "* Removing the dense layers reduces overfitting. NiN has dramatically fewer parameters.\n",
    "* The NiN design influenced many subsequent convolutional neural networks designs.\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. Tune the hyper-parameters to improve the classification accuracy.\n",
    "1. Why are there two $1\\times 1$ convolutional layers in the NiN block? Remove one of them, and then observe and analyze the experimental phenomena.\n",
    "1. Calculate the resource usage for NiN\n",
    "    * What is the number of parameters?\n",
    "    * What is the amount of computation?\n",
    "    * What is the amount of memory needed during training?\n",
    "    * What is the amount of memory needed during inference?\n",
    "1. What are possible problems with reducing the $384 \\times 5 \\times 5$ representation to a $10 \\times 5 \\times 5$ representation in one step?\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Java",
   "language": "java",
   "name": "java"
  },
  "language_info": {
   "codemirror_mode": "java",
   "file_extension": ".jshell",
   "mimetype": "text/x-java-source",
   "name": "Java",
   "pygments_lexer": "java",
   "version": "14.0.2+12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
